package com.ruoyi.project.experiment.onlineexperiment.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.experiment.onlineexperiment.domain.TbExperiment;
import com.ruoyi.project.experiment.onlineexperiment.service.ITbExperimentService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.mapper.UserMapper;
import com.ruoyi.project.system.user.service.IUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;

import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 在线实验项目Controller
 * 
 * @author lvyongwei
 * @date 2020-09-17
 */
@Controller
@RequestMapping("/system/experiment")
public class TbExperimentController extends BaseController
{
    private String prefix = "system/experiment";

    @Autowired
    private ITbExperimentService tbExperimentService;

    @Autowired
    private UserMapper userMapper;

    @RequiresPermissions("system:experiment:view")
    @GetMapping()
    public String experiment()
    {
        return prefix + "/experiment";
    }

    /**
     * 查询在线实验项目列表
     */
    @RequiresPermissions("system:experiment:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TbExperiment tbExperiment)
    {
        startPage();
        List<TbExperiment> list = tbExperimentService.selectTbExperimentList(tbExperiment);
        return getDataTable(list);
    }

    /**
     * 导出在线实验项目列表
     */
    @RequiresPermissions("system:experiment:export")
    @Log(title = "在线实验项目", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TbExperiment tbExperiment)
    {
        List<TbExperiment> list = tbExperimentService.selectTbExperimentList(tbExperiment);
        ExcelUtil<TbExperiment> util = new ExcelUtil<TbExperiment>(TbExperiment.class);
        return util.exportExcel(list, "experiment");
    }

    /**
     * 新增在线实验项目
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存在线实验项目
     */
    @RequiresPermissions("system:experiment:add")
    @Log(title = "在线实验项目", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(TbExperiment tbExperiment, MultipartFile file) throws IOException {
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        tbExperiment.setExperimentPhoto(fileName);
        return toAjax(tbExperimentService.insertTbExperiment(tbExperiment));
    }

    /**
     * 修改在线实验项目
     */
    @GetMapping("/edit/{experimentId}")
    @RequiresPermissions("admin,experimentManage")
    public String edit(@PathVariable("experimentId") Long experimentId, ModelMap mmap)
    {
        TbExperiment tbExperiment = tbExperimentService.selectTbExperimentById(experimentId);
        mmap.put("tbExperiment", tbExperiment);
        return prefix + "/edit";
    }

    /**
     * 修改保存在线实验项目
     */
    @RequiresPermissions("system:experiment:edit")
    @Log(title = "在线实验项目", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TbExperiment tbExperiment, MultipartFile file) throws IOException {
        if(!StringUtils.isNull(file)){
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            tbExperiment.setExperimentPhoto(fileName);
        }
        return toAjax(tbExperimentService.updateTbExperiment(tbExperiment));
    }

    /**
     * 删除在线实验项目
     */
    @RequiresPermissions("system:experiment:remove")
    @Log(title = "在线实验项目", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(tbExperimentService.deleteTbExperimentByIds(ids));
    }


    /**
     * 修改实验开放状态
     * @param tbExperiment
     * @return
     */
    @Log(title = "修改实验开放状态", businessType = BusinessType.UPDATE)
    @RequiresPermissions("admin,experimentManage")
    @PostMapping( "/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(TbExperiment tbExperiment){
         return toAjax(tbExperimentService.changeStatus(tbExperiment));
    }

    /**
     * 指派教师
     */
    @GetMapping("/asign")
    public String assign(Long experimentId, ModelMap mmap)
    {
        /**
         * 获取对象
         */
        TbExperiment tbExperiment = tbExperimentService.selectTbExperimentById(experimentId);
        /**
         * 获取所有的教师
         */
        List<User> list = userMapper.getAllTeacher();
        /**
         * 集合存放指派的教师
         */
        List<User> haveAsign = new ArrayList<User>();
        mmap.addAttribute("tbExperiment",tbExperiment);
        /**
         * 获取已经指派的教师
         */
        List<Long> teacherIds = tbExperimentService.getAsignTeacher(experimentId);

        System.out.println(list);
        System.out.println(teacherIds);
        for(int i=0;i<list.size();i++){
            boolean flag = false;
            for(Long tid:teacherIds){
                if(list.get(i).getUserId().longValue()==tid.longValue()){
                    haveAsign.add(list.get(i));
                    flag = true;
                }
            }
            if(flag){
                list.remove(list.get(i));
                i--;
            }
        }
        mmap.addAttribute("teacher",list);
        mmap.addAttribute("asignTeacher",haveAsign);
        /**
         * 查询所有角色是教师的用户
         */
        return prefix + "/asign";
    }


    /**
     * 指派教师
     * @return
     */
    @PostMapping("/addTeacher")
    @ResponseBody
    public AjaxResult addTeacher(String experimentId,@RequestParam(value="userIds[]")String[] userIds){
        if(userIds.length == 1 && userIds[0].equals("null")){
            return AjaxResult.error("无其他教师指派");
        }
        List<Long> users = new ArrayList<Long>();
        for(String id:userIds){
            users.add(Long.valueOf(id));
        }
        return toAjax(tbExperimentService.addTeacher(Long.valueOf(experimentId),users));
    }
}
